﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MMD_Morph_NoteHelp
{
    #region --- Data Structures ---
    /// <summary>
    /// 存储手动指定的 ComboBox 和 Edit 控件的数据。
    /// </summary>
    public struct MorphSlotData
    {
        public string CurrentValue { get; set; }
        public List<string> AllMorphNames { get; set; }
    }


    #endregion

    /// <summary>
    /// 封装了与统一的 AHK 脚本 (MMD_ControlHelper.exe) 交互的逻辑。
    /// </summary>
    public static class AhkHelper
    {
        private static readonly string AhkAppName = "MMD_ControlHelper.exe"; // 调用AHK脚本-枚举控件

        #region --- Public Methods ---
        /// <summary>
        /// 获取指定控件的文本值。
        /// </summary>
        public static async Task<string> GetControlText(string classNN)
        {
            var result = await CallAhkProcess("get_text", classNN);
            return result.ExitCode == 0 ? result.Output : null;
        }

        /// <summary>
        /// 获取 ComboBox 控件中的所有项目列表。
        /// </summary>
        public static async Task<List<string>> GetComboBoxItems(string classNN)
        {
            var result = await CallAhkProcess("list_combobox", classNN);
            if (result.ExitCode == 0)
            {
                return result.Output.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            }
            Debug.WriteLine($"AHK Error (GetComboBoxItems for {classNN}): {result.Error}");
            return new List<string>();
        }

        /// <summary>
        /// 一次性获取一个表情槽位的所有数据（当前值和所有可选项目）。
        /// </summary>
        public static async Task<MorphSlotData?> GetMorphSlotData(string comboBoxClassNN, string editClassNN)
        {
            var result = await CallAhkProcess("get_slot_data", comboBoxClassNN, editClassNN);
            if (result.ExitCode != 0)
            {
                Debug.WriteLine($"AHK Error (GetMorphSlotData for {comboBoxClassNN}/{editClassNN}): {result.Error}");
                return null;
            }

            var lines = result.Output.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            if (lines.Length == 0) return new MorphSlotData { CurrentValue = "", AllMorphNames = new List<string>() };

            string currentValue = "";
            List<string> allMorphs;

            if (lines[0].StartsWith("VALUE:"))
            {
                currentValue = lines[0].Substring("VALUE:".Length);
                allMorphs = lines.Skip(1).ToList();
            }
            else
            {
                currentValue = "Error: Invalid Format";
                allMorphs = lines.ToList();
            }

            return new MorphSlotData { CurrentValue = currentValue, AllMorphNames = allMorphs };
        }

        /// <summary>
        /// 根据一个 ComboBox 的 ClassNN，自动查找其配对的 Edit 控件，并返回两者的数据。
        /// </summary>
        public static async Task<PairedControlData?> GetPairedControlData(string comboBoxClassNN)
        {
            var result = await CallAhkProcess("get_paired_data", comboBoxClassNN);
            if (result.ExitCode != 0)
            {
                Debug.WriteLine($"AHK Error (GetPairedControlData for {comboBoxClassNN}): {result.Error}");
                return null;
            }

            var data = new PairedControlData();
            var dict = result.Output.Split('|')
                .Select(p => p.Split(new[] { ':' }, 2))
                .Where(p => p.Length == 2)
                .ToDictionary(p => p[0], p => p[1]);

            dict.TryGetValue("COMBO_TEXT", out var comboText);
            dict.TryGetValue("EDIT_VALUE", out var editValue);
            data.ComboBoxText = comboText;
            data.EditValue = editValue;

            return data;
        }
        #endregion

        #region --- Core Process Caller ---
        private struct ProcessResult
        {
            public int ExitCode;
            public string Output;
            public string Error;
        }

        private static async Task<ProcessResult> CallAhkProcess(params string[] args)
        {
            string ahkAppPath = Path.Combine(Application.StartupPath, "config", AhkAppName);
            if (!File.Exists(ahkAppPath))
            {
                MessageBox.Show($"错误：未找到核心组件 {Path.Combine("config", AhkAppName)}！", "组件丢失", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return new ProcessResult { ExitCode = -1, Error = "AHK executable not found." };
            }

            var startInfo = new ProcessStartInfo
            {
                FileName = ahkAppPath,
                Arguments = string.Join(" ", args.Select(arg => $"\"{arg}\"")),
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                StandardOutputEncoding = System.Text.Encoding.UTF8
            };

            using (var process = new Process { StartInfo = startInfo })
            {
                process.Start();
                var outputTask = process.StandardOutput.ReadToEndAsync();
                var errorTask = process.StandardError.ReadToEndAsync();

                // 等待所有流读取完毕
                await Task.WhenAll(outputTask, errorTask);

                // 使用 Task.Run 来异步等待进程退出，以兼容旧版 .NET Framework
                await Task.Run(() => process.WaitForExit());

                return new ProcessResult
                {
                    ExitCode = process.ExitCode,
                    Output = (await outputTask).Trim(),
                    Error = (await errorTask).Trim()
                };
            }
        }
        #endregion
    }
}